<template>
  <div class="papers">
    <!-- 顶部导航栏 -->
    <top-bar
        v-show="navShow"
        :isleftarrow="isleftarrow"
        :title="title"
        :rightIcon="rightIcon"
        :rightIconUser="rightIconUser"
    ></top-bar>
    <!-- 占位空间 -->
    <div class="space"></div>
    <!-- 顶部标签栏（用于区分视频专区与文章专区）后期优化应进行组件封装 -->
    <div class="tabArea">
      <van-tabs v-model="tabActive">
        <van-tab title="公告" name="bulletin" v-if="this.userRole==='ROLE_admin'||this.userRole==='ROLE_user'">
          <!--    下拉刷新      -->
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <!--      vantlist公告列表      -->
            <van-list
                v-model="loading"
                :finished="finished"
                finished-text="真的没有了"
                @load="onLoad">
              <van-panel v-for="item in bulletinList" :title="item.title" :desc="item.author" :status="item.date">
                <div>{{item.contents}}</div>
                <template #footer>
                  <van-button size="small" @click="updateBulletinData(item)">修改</van-button>
                  <van-button size="small" type="danger" @click="deleteBulletinData(item)">删除</van-button>
                </template>
              </van-panel>
              <!--     修改信息覆盖页       -->
              <van-overlay :show="fixOverLayShow" @click="fixOverLayShow=false">
                <div class="wrapper" @click.stop>
                  <div class="block">
                    <!--       公告标题         -->
                    <div class="gg-title">
                      <span style="margin-left: 20px;margin-top: 5px">修改公告</span>
                      <span style="margin-left: 80px;margin-top: 5px" v-if="this.$store.getters.userRoleInfo==='ROLE_admin'">可见:</span>
                      <select name="" id="adminFixChooseArea" v-if="this.$store.getters.userRoleInfo==='ROLE_admin'">
                        <option value="hysk">红阳三矿</option>
                        <option value="mdt">马道头</option>
                        <option value="sys">双鸭山</option>
                        <option value="dt">大同</option>
                        <option value="pds">平顶山</option>
                        <option value="all">所有可见</option>
                      </select>
                    </div>
                    <!--       公告表单         -->
                    <div class="gg-form">
                      <div class="gg-form-item">
                        <label for="ggtitle" style="width: 20%;text-align: center;height: 80%;margin-top: 5px">标题</label>
                        <textarea name="ggtitle" id="fixBulletinTitle" style="width: 80%" placeholder="请输入标题" v-model="bulletin.bulletinTitle"></textarea>
                      </div>
                      <textarea placeholder="请输入公告内容" name="gginfo" style="height: 86.5%;width: 94%;margin-top: 5px" v-model="bulletin.bulletinContent"></textarea>
                    </div>
                    <!--        公布按钮与area可见筛选部分        -->
                    <div class="gg-btn">
                      <van-button round type="warning" @click="fixOverLayShow=false" style="margin: 0 auto">取消</van-button>
                      <van-button round type="info" style="margin: 0 auto" @click="requestUpdateData">修改</van-button>
                    </div>
                  </div>
                </div>
              </van-overlay>
              <!--    发布信息覆盖页      -->
              <van-overlay :show="overlayshow" @click="overlayshow=false">
                <div class="wrapper" @click.stop>
                  <div class="block">
                    <!--       公告标题         -->
                    <div class="gg-title">
                      <span style="margin-left: 20px;margin-top: 5px">编辑公告</span>
                      <span style="margin-left: 80px;margin-top: 5px" v-if="this.$store.getters.userRoleInfo==='ROLE_admin'">可见:</span>
                      <select name="" id="adminChooseArea" v-if="this.$store.getters.userRoleInfo==='ROLE_admin'">
                        <option value="hysk">红阳三矿</option>
                        <option value="mdt">马道头</option>
                        <option value="sys">双鸭山</option>
                        <option value="dt">大同</option>
                        <option value="pds">平顶山</option>
                        <option value="all">所有可见</option>
                      </select>
                    </div>
                    <!--       公告表单         -->
                    <div class="gg-form">
                      <div class="gg-form-item">
                        <label for="ggtitle" style="width: 20%;text-align: center;height: 80%;margin-top: 5px">标题</label>
                        <textarea name="ggtitle" id="ggtitle" style="width: 80%" placeholder="请输入标题" v-model="bulletin.bulletinTitle"></textarea>
                      </div>
                      <textarea placeholder="请输入公告内容" name="gginfo" style="height: 86.5%;width: 94%;margin-top: 5px" v-model="bulletin.bulletinContent"></textarea>
                    </div>
                    <!--        公布按钮与area可见筛选部分        -->
                    <div class="gg-btn">
                      <van-button round type="warning" @click="overlayshow=false" style="margin: 0 auto">取消</van-button>
                      <van-button round type="info" style="margin: 0 auto" @click="addBulletinData">确定</van-button>
                    </div>
                  </div>
                </div>
              </van-overlay>
            </van-list>
            <!--    悬浮按钮位置      -->
            <div class="float-button" v-if="overlayshow === false">
              <p style="color: white" @click="overlayshow=true">发布</p>
            </div>
            <div class="space"></div>
          </van-pull-refresh>
        </van-tab>
        <van-tab title="相关科普" name="a">
          <van-cell v-for="item in popuScienceItem" :title="item.text" is-link @click="getPopuItem(item.text)"></van-cell>
        </van-tab>
      </van-tabs>
    </div>
    <footer-bar></footer-bar>
  </div>
</template>

<script>
import FooterBar from "../components/FooterBar.vue";
import TopBar from "../components/TopBar.vue";
import {Toast} from 'vant';
import { Dialog } from 'vant';
import Qs from "qs";
import {getBulletins, deleteBulletin, addBulletin,updateBulletin} from "../request/api/bulletinData";
export default {
  components: { FooterBar, TopBar },
  name: "Papers",
  data() {
    return {
      title:"",
      userRole:this.$store.getters.userRoleInfo,
      userArea:this.$store.state.userInfo.userArea,
      isleftarrow: "",
      navShow: true,
      rightIcon: "",
      rightIconUser: "",
      tabActive: this.$store.state.bulletinsData.tabActive,
      overlayshow: false,
      fixOverLayShow:false,
      //当前触发列表底部计数器
      pageNum: 0,
      refreshing:false,
      isLoading:false,
      loading:false,
      finished:false,
      bulletin:{
        //公告标题
        bulletinTitle: null,
        //公告内容
        bulletinContent: null,
        //bulletin ID
        bulletinId: null,
        //bulletin area
        bulletinArea:null,
        //date
        bulletinDate:null
      },
      //公告信息列表
      bulletinList:[],
      //科普模块列表
      popuScienceItem: this.$store.state.popuScienceItem
    };
  },
  created() {
    // this.getBulletinData(this.userArea,this.pageNum);
  },
  mounted() {
    this.title = this.$route.meta.title;
    this.isleftarrow = this.$route.meta.isleftarrow;
    this.rightIcon = this.$route.meta.rightIcon;
    this.rightIconUser = this.$route.meta.rightIconUser;
  },
  watch: {
    $route(to, from) {
      this.title = to.meta.title;
      this.isleftarrow = from.meta.isleftarrow;
    },
  },
  methods:{
    //科普单元跳转
    getPopuItem(data){
      //change page title storage
      this.$store.commit("changeJumpPageChnInfo",data);
      //jump page
      this.$router.push({
        name:'PopuScience'
      });
      this.$store.commit("changeBulletinInfo","a");
    },
    //列表到达底部触发分页加载方法
    onLoad() {
      setTimeout(() => {
        if (this.refreshing){
          //clear the list
          this.bulletinList = [];
          //set the pageNum equal to one value
          this.pageNum = 1;
          this.refreshing = false;
          this.getBulletinData(this.userArea,this.pageNum);
          this.loading = false;
        }else {
          this.pageNum++;
          this.getBulletinData(this.userArea,this.pageNum);
          this.loading = false;
        }
      }, 1000);
    },
    //下拉刷新请求方法
    onRefresh(){
      // 清空列表数据
      this.finished = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
    //获取公告数据接口方法
    getBulletinData(area,pageNum){
      //需要前端参数: area pageNum
      const formText={
        area: area,
        pageNum: pageNum
      };
      //转换formText为formJSON
      const formJSON = Qs.parse(formText);
      getBulletins(formJSON)
          .then(response => {
            //打印输出测试
            console.log(response.data.bulletinMessage.content);
            if (response.data.bulletinMessage.content.length === 0){
              this.finished = true;
            }else {
              for (let i=0;i<response.data.bulletinMessage.content.length;i++){
                this.bulletinList.push(response.data.bulletinMessage.content[i]);
              }
            }
          })
    },
    //delete bulletin interface
    deleteBulletinData(data){
      Dialog.confirm({
        message: '确认删除？',
        theme: 'round-button',
      }).then(() => {
        //通过id删除数据根据删除后返回的 isSucceed 值进行判断是否删除成功，成功则触发刷新方法，否则触发警告通知
        const formText = {
          id:data.id
        };
        const formJSON = Qs.parse(formText);
        deleteBulletin(formJSON)
            .then(response => {
              var isDeleted = response.data.isSucceed;
              if (isDeleted === 'true'){
                Toast({
                  message:'删除成功',
                  duration:1000,
                  forbidClick: true,
                });
                //删除成功，刷新数据列表
                this.refreshing = true;
                this.onRefresh();
              }else {
                Toast({
                  message:'删除失败',
                  duration:1000,
                  forbidClick: true,
                })
              }
            })
      }).catch(() => {
            // on cancel
          });
    },
    //update bulletin interface param:{all of data}
    updateBulletinData(data){
      this.fixOverLayShow = true;
      //点击修改按钮，获取该条数据的item全部数据作为参数，填充进数据框中，并进行判断。
      this.bulletin.bulletinTitle = data.title;
      this.bulletin.bulletinContent = data.contents;
      this.bulletin.bulletinId = data.id;
      if (this.userRole === 'ROLE_admin'){
        var select = document.getElementById('adminFixChooseArea');
        var i = select.value;
        i = data.area;
        this.bulletin.bulletinArea = i;
      }else {
        this.bulletin.bulletinArea = this.userArea;
      }
      var preDate = new Date();
      const bulletinMonth = preDate.getMonth()+1;
      this.bulletin.bulletinDate = preDate.getFullYear()+'-'+bulletinMonth+'-'+preDate.getDate();
    },
    requestUpdateData(){
      //判断各个数据项的值是否合法
      if (this.bulletin.bulletinTitle === null || this.bulletin.bulletinContent === null){
        Toast.fail("输入内容不能为空");
      }else {
        if (this.bulletin.bulletinTitle.length > 55) {
          Toast.fail('标题过长');
        }
        if (this.bulletin.bulletinContent.length > 500) {
          Toast.fail('内容大于500字')

        }
        else {
          Dialog.alert({
            message: '确认修改？',
            theme: 'round-button',
          }).then(() => {
            const formText={
              id : this.bulletin.bulletinId,
              area:this.bulletin.bulletinArea,
              title:this.bulletin.bulletinTitle,
              date:this.bulletin.bulletinDate,
              contents:this.bulletin.bulletinContent,
              author:this.$store.state.userInfo.nickName
            }
            const formJSON = Qs.parse(formText);
            updateBulletin(formJSON)
                .then(response =>{
                  console.log(response.data.isSucceed);
                  if (response.data.isSucceed === 'true'){
                    this.fixOverLayShow = false;
                    Toast.success('修改成功');
                    this.refreshing = true;
                    this.onRefresh();
                  }else {
                    this.fixOverLayShow = false;
                    Toast.fail('something wrong');
                  }
                })
          });
        }
      }
    },
    //add bulletin interface param:{ all of data }
    addBulletinData(){
      //判断各个数据项的值是否合法
      if (this.bulletin.bulletinTitle === null || this.bulletin.bulletinContent === null){
        Toast.fail("输入内容不能为空");
      }else {
        if (this.bulletin.bulletinTitle.length > 55){
          Toast.fail('标题过长');
        }
        if (this.bulletin.bulletinContent.length > 500){
          Toast.fail('内容大于500字')
        }
        else {
          //判断当前身份
          var i;
          console.log(this.userRole);
          if (this.userRole ==='ROLE_admin'){
            var select = document.getElementById('adminChooseArea');
            i = select.value
          }else {
            i = this.userArea;
          }
          var preDate = new Date();
          const bulletinMonth = preDate.getMonth()+1;
          var time = preDate.getFullYear()+'-'+bulletinMonth+'-'+preDate.getDate();
          console.log(time)
          //获取相应数值
          const formText={
            area: i,
            title: this.bulletin.bulletinTitle,
            date: time,
            author: this.$store.getters.userAreaInfo,
            contents: this.bulletin.bulletinContent
          };
          const formJSON = Qs.parse(formText);
          addBulletin(formJSON)
              .then(response =>{
                var isAdd = response.data.isSucceed;
                if (isAdd === 'true'){
                  this.overlayshow = false;
                  Toast.success('添加信息成功');
                  //触发刷新条件
                  this.refreshing = true;
                  //开始刷新
                  this.onRefresh();
                }
                else {
                  this.overlayshow = false;
                  Toast.fail('发布公告失败');
                }
              })
        }
      }
    }
  }
};
</script>

<style scoped>
.space{
  height: 40px;
}
.float-button{
  position: fixed;
  height: 55px;
  width: 55px;
  bottom: 90px;
  right: 4px;
  z-index: 100;
  background-color: aqua;
  opacity: 0.6;
  border-radius: 50%;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 80%;
  height: 83%;
  border-radius: 5px;
  background-color: #fff;
}
.gg-title{
  height: 6%;
  width: 100%;
  border-bottom: 1px solid black;
  text-align: center;
  font-size: 15px;
  display: flex;
}
.gg-form{
  height: 75%;
  width: 90%;
  margin: 15px auto;
  /*border: 1px solid black;*/
  border-radius: 5px;
}
.gg-form-item{
  height: 10%;
  width: 100%;
  display: flex;
  background: lightgray;
  margin-top: 3px;
}
.gg-btn{
  display: flex;
  height: 10%;
  width: 100%;
}
</style>